//
//  OYRefreshControl.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/7.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit


public enum refreshType {
    /// 松手状态
    case release
    /// 下拉状态
    case pull
    /// 加载中状态
    case refresh
}
class OYRefreshControl: UIControl {

    fileprivate var refreshingType:refreshType = .pull {
        didSet {
            switch refreshingType {
            case .pull:
//                print("下拉刷新")
                indicatorView.stopAnimating()
                // 判断如果是从刷新状态进入下拉状态的，再改变scrollView的contentInset，因为默认状态是下拉状态
                if oldValue == .refresh {
                    self.scrollView.contentInset.top -= 50
                }
                refreshIconView.isHidden = false
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.refreshIconView.transform = CGAffineTransform.identity
                })

                indicatingLabel.text = "下拉刷新"
                
            case .release:
//                print("释放刷新")
                indicatingLabel.text = "释放刷新"
                UIView.animate(withDuration: 0.25, animations: {
                    self.refreshIconView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                
            case .refresh:
//                print("加载中")
                refreshIconView.isHidden = true
                indicatorView.startAnimating()
                indicatingLabel.text = "加载中..."
                // 设置悬停
                self.scrollView.contentInset.top += 50
                // 发送消息
                self.sendActions(for: .valueChanged)
                
            }
        }
    }
    
    func endRefreshing() {
 
        refreshingType = .pull
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
       
        setupUI()
    }
    
     // MARK: -控件的懒加载
    private lazy var scrollView = UIScrollView()
    private lazy var refreshIconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var indicatingLabel: UILabel = {
        let label = UILabel()
        label.text = "下拉刷新"
        label.textColor = UIColor.lightGray
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)

    
     // MARK: -添加子控件并进行布局
    func setupUI() {
    
        addSubview(refreshIconView)
        addSubview(indicatingLabel)
        addSubview(indicatorView)
        
        // 系统自带约束方式设置约束
        refreshIconView.translatesAutoresizingMaskIntoConstraints = false
        indicatingLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
    
        addConstraint(NSLayoutConstraint(item: refreshIconView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -50))
        addConstraint(NSLayoutConstraint(item: refreshIconView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatingLabel, attribute: .centerY, relatedBy: .equal, toItem: refreshIconView, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatingLabel, attribute: .left, relatedBy: .equal, toItem: refreshIconView, attribute: .right, multiplier: 1, constant: 10))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: refreshIconView, attribute: .centerX, multiplier: 1, constant: -50))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: refreshIconView
            , attribute: .centerY, multiplier: 1, constant: 0))
        
      
    }
    
     // MARK: -在父视图加载本视图时候调用，可以拿到父视图
    override func willMove(toSuperview newSuperview: UIView?) {
        
        // MARK: -设置控件自身的大小和位置
        self.frame.size = CGSize(width: ScreenWidth, height: 50)
        self.backgroundColor = UIColor.brown
        self.frame.origin.y = -50
        
        scrollView = newSuperview as! UIScrollView
        // KVO方式监测父控件的滑动距离
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
        
    }
    
     // MARK: -KVO监听方法，在此根据父控件的滑动距离变化设置本控件的不同状态
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentOffset = scrollView.contentOffset
         // MARK: -使用contentInset增强通用性
        let refreshOffset = -(scrollView.contentInset.top + self.frame.size.height)
        
        if scrollView.isDragging {

            // 如果下拉距离达到要求，并且目前类型是pull
            if contentOffset.y < refreshOffset && refreshingType == .pull {
                // 将状态切换至释放更新
//                print("释放更新")
                refreshingType = .release
            } else if contentOffset.y > refreshOffset && refreshingType == .release {
                // 将状态切换至下拉刷新
//                print("下拉刷新")
                refreshingType = .pull
            }
            
        }else {
            // 将状态切换至加载中,只有当状态是释放更新的时候，才能进入
            if refreshingType ==  .release{
//                print("加载中...")
                refreshingType = .refresh
                
            }
        }
        
//        print(contentOffset)
        
        
    }
    
    deinit {
        // 移除观察者
        scrollView.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    
}
